/*
 * 文件名：CustomFormAuthenticationFilter.java
 * 版权： Copyright 2002-2007 12316yun. All Rights Reserved.
 * 描述：〈描述〉

 * 修改人：王钰玺
 * 修改时间：2018/4/27 11:09
 * 修改单号：〈修改单号〉
 * 修改内容：〈修改内容〉
 */
package com.yun12316.framework.shiro.realm;

import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 拦截过期session的请求，并且以ajax形式返回
 * <p>
 * <p>拦截过期session的请求，并且以ajax形式返回</p>
 *
 * @author 王钰玺 2018/4/27
 * @see
 * @since 1.0
 */
public class CustomFormAuthenticationFilter extends FormAuthenticationFilter {

    private static Integer  HTTP_STATUS_SESSION_EXPIRE =  901;

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                return executeLogin(request, response);
            } else {
                // 放行 allow them to see the login page ;)
                return true;
            }
        } else {
            HttpServletRequest httpRequest = WebUtils.toHttp(request);

            if (isAjax(httpRequest)) {

                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.sendError(HTTP_STATUS_SESSION_EXPIRE);

                return false;

            } else {
                saveRequestAndRedirectToLogin(request, response);
            }

            return false;
        }
    }

    /**
     * 判断ajax请求
     * @param request
     * @return
     */
    boolean isAjax(HttpServletRequest request){
        return  (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
    }
}
